import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';

const Buttom2 = () => {
    const chartRef = useRef(null);
    const [chartInstance, setChartInstance] = useState(null);
    const [data, setData] = useState([
        { type: '黄化曲叶病', value: 2 },
        { type: '灰叶斑病', value: 0 },
        { type: '灰霉病', value: 1 },
        { type: '棒袍褐斑病', value: 2 },
    ]);
    const [step, setStep] = useState(0);

    useEffect(() => {
        const initChart = (instance) => {
            instance.setOption({
                xAxis: {
                    type: 'category',
                    data: data.map((item) => item.type),
                },
                yAxis: {
                    type: 'value',
                    min: 0,
                    max: 5,
                },
                series: [
                    {
                        data: data.map((item) => item.value),
                        type: 'bar',
                        colorBy: 'data',
                    },
                ],
            });
        };

        if (chartRef.current) {
            const instance = echarts.init(chartRef.current);
            setChartInstance(instance);
            initChart(instance);
        }
    }, [data]);

    useEffect(() => {
        const interval = setInterval(() => {
            setData((prevData) => {
                const newData = [...prevData];
                if (step === 0) {
                    newData[0].value += 1;
                    newData[1].value += 1;
                } else if (step === 1) {
                    newData[3].value += 1;
                }
                setStep((prevStep) => (prevStep + 1) % 2);
                return newData;
            });
        }, 12000);

        return () => clearInterval(interval);
    }, [step]);

    useEffect(() => {
        const updateChart = () => {
            if (chartInstance) {
                chartInstance.setOption({
                    series: [
                        {
                            data: data.map((item) => item.value),
                        },
                    ],
                });
            }
        };

        updateChart();
    }, [data, chartInstance]);

    return (
        <div>
            <div ref={chartRef} style={{ width: '100%', height: '170px' }}></div>
        </div>
    );
};

export default Buttom2;
